<template>
  <div>
    <ImageInput :urls="modelValue" @remove="removeModelValue" @click="resourceSelectionControlVisible = true"></ImageInput>
    <el-dialog
      v-model="resourceSelectionControlVisible"
      align-center
      min-width="700px;"
      destroy-on-close
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <template #header> {{ $t("resources.title") }} </template>
      <div class="common-layout" style="height: 500px">
        <el-container style="height: 100%">
          <Category @set-category-id="setCategoryId" />
          <ImageList
            :type="props.type"
            :categoryId="categoryId"
            :number="props.number"
            @click="clickImages"
            @selected="updateModelValue"
          />
        </el-container>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup name="Resources">
import ImageInput from "./ImageInput.vue";
import Category from "./Category.vue";
import ImageList from "./ImageList.vue";
import { ref, onBeforeMount, watch } from "vue";

const resourceSelectionControlVisible = ref(false);
const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  number: {
    type: Number,
    default: 1
  },
  type: {
    type: Number
  }
});

const modelValue = ref([]);
const setModelValue = val => {
  modelValue.value = val ? val.split(",") : [];
};

const categoryId = ref("");
const setCategoryId = id => {
  categoryId.value = id;
};

const queueList = ref([]);
const clickImages = list => {
  queueList.value = list;
};

const emit = defineEmits(["update:modelValue"]);
const updateModelValue = () => {
  modelValue.value = modelValue.value.concat(queueList.value);
  modelValue.value = modelValue.value.splice(0, props.number);
  queueList.value = [];
  emit("update:modelValue", modelValue.value.join(","));
  resourceSelectionControlVisible.value = false;
};

const removeModelValue = urls => {
  modelValue.value = urls;
  updateModelValue();
};

onBeforeMount(() => {
  setModelValue(props.modelValue);
});
watch(
  () => props.modelValue,
  newValue => {
    setModelValue(newValue);
  }
);
</script>
